package com.haha.helloworld.recyclerview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.haha.helloworld.R;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

//增加一个泛型
public class HorAdapter extends RecyclerView.Adapter<HorAdapter.LinearViewHolder> {

    private Context myContext;
    private OnItemClickListener myOnItemClickListener;

    public HorAdapter(Context context, OnItemClickListener onItemClickListener){
        this.myContext=context;
        this.myOnItemClickListener=onItemClickListener;
    }


    @NonNull
    @Override
    public HorAdapter.LinearViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        return new LinearViewHolder(LayoutInflater.
                from(myContext).
                inflate(R.layout.layout_linear_item,parent,false));
    }
    //设置控件的内容
    @Override
    public void onBindViewHolder(@NonNull HorAdapter.LinearViewHolder holder, int position) {
        holder.textView.setText("Hello World!");
        //onclick事件方式一：在Adapter这里定义一个onclick事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(myContext,"点击了第"+position+"个item",Toast.LENGTH_SHORT).show();
                //方式二：
                //这里就会去调用onclick方法，onclick方法写在LinearRecyclerViewActivity里边的
                myOnItemClickListener.onClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return 30;
    }

    //自己写一个LinearViewHolder
    class LinearViewHolder extends RecyclerView.ViewHolder{
        //声明一下自己的控件
        private TextView textView;

        public LinearViewHolder(@NonNull View itemView) {
            super(itemView);
            textView=(TextView) itemView.findViewById(R.id.tv_title);
        }
    }


    //onclick事件方式二：在Adapter这里定义一个onclick事件接口
    public interface OnItemClickListener{
        void onClick(int pos);
    }

}
